﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Helpers;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel.YTJYAdmin.Course;
using SiteAPI.Controllers.Common;

namespace SiteAPI.Controllers.Business
{
    /// <summary>
    /// 课程相关控制器
    /// </summary>
    public class CourseController : BaseApiController
    {
        /// <summary>
        /// 课程相关操作service
        /// </summary>
        private ECourseService eCourseService => new ECourseService();

        /// <summary>
        /// 套餐相关操作service
        /// </summary>
        private EPackageService ePackageService => new EPackageService();

        /// <summary>
        /// 学习记录service
        /// </summary>
        private EVideoStudySumService eVideoStudySumService => new EVideoStudySumService();

        /// <summary>
        /// 视频学习记录service
        /// </summary>
        private EVideoStudyLogService eVideoStudyLogService => new EVideoStudyLogService();

        /// <summary>
        /// 获取套餐下的课程表
        /// </summary>
        [HttpPost, Route("api/ytjysite/ECourse/GetModelList")]
        [AllowAnonymous]
        public ServiceResponse<SiteCourseViewModel> GetModelList(SiteCourseRequeset request)
        {
            var viewModel = eCourseService.GetSiteModelList(request, CurrentUserModel.UserId);
            var package = ePackageService.Find(p => !p.IsDelete && p.Id == request.PackageId);
            if (package.IsNotNull())
                viewModel.Description = package.Description ?? string.Empty;

            return ServiceResponse<SiteCourseViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 获取首页免费课程列表
        /// </summary>
        [HttpPost, Route("api/ytjysite/ECourse/GetFreeModelList")]
        [AllowAnonymous]
        public ServiceResponse<FreeCourseViewModel> GetFreeModelList(FreeCourseRequest request)
        {
            var viewModel = eCourseService.GetFreeModelList(request);

            return ServiceResponse<FreeCourseViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 获取课程详情
        /// </summary>
        [HttpPost, Route("api/ytjysite/ECourse/GetModelDetailList")]
        [AllowAnonymous]
        public ServiceResponse<CourseDetailViewModel> GetModelDetailList(CourseDetailRequest request)
        {
            var viewModel = eCourseService.GetModelDetailList(request, CurrentUserModel.UserId);
            var model = eCourseService.Find(c => !c.IsDelete && c.Id == request.CourseId);
            if (model.IsNotNull())
                viewModel.Description = model.Description;

            return ServiceResponse<CourseDetailViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 提交视频进度
        /// </summary>
        [HttpPost, Route("api/ytjysite/ECourse/SubmitVideoLog")]
        public ServiceResponse<SubmitVideoLogViewModel> SubmitVideoLog(SubmitVideoLogRequest request)
        {
            var userId = CurrentUserModel?.UserId ?? Guid.Empty;

            if (userId == Guid.Empty)
                return ServiceResponse<SubmitVideoLogViewModel>.ErrorResponse(CommonConst.Msg_NoLogin);

            var studyLog = eVideoStudyLogService.Find(e => !e.IsDelete && e.Id == request.StudyLogId);
            if (studyLog.IsNull())//新增一条学习记录
            {
                studyLog = new EVideoStudyLog
                {
                    Id = Guid.NewGuid(),
                    PackageId = request.PackageId,
                    CourseId = request.CourseId,
                    ChapterId = request.ChapterId,
                    VideoId = request.VideoId,
                    UserId = userId,
                    IsDelete = false,
                    OrgCode = CurrentUserModel?.OrgCode ?? string.Empty,
                    CreateUserId = userId,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    UpdateUserId = userId,
                    StartTime = DateTime.Now,
                    EndTime = DateTime.Now,
                    IsFinish = request.IsFinish,
                    IsUsed = true,
                    TimeSpan = 0
                };
                request.StudyLogId = studyLog.Id;
                eVideoStudyLogService.AddNoSaveChange(studyLog);
            }
            else  //更新观看记录结束时间
            {
                studyLog.EndTime = DateTime.Now;
                studyLog.IsFinish = request.IsFinish;

                var ts = (studyLog.EndTime - studyLog.StartTime).TotalSeconds;
                studyLog.TimeSpan = (int)ts;

                studyLog.UpdateTime = DateTime.Now;
                studyLog.UpdateUserId = userId;

                eVideoStudyLogService.UpdateNoSaveChange(studyLog);
            }

            var sum = eVideoStudySumService.Find(e => !e.IsDelete && e.UserId == userId && e.PackageId == request.PackageId && e.CourseId == request.CourseId && e.ChapterId == request.ChapterId && e.VideoId == request.VideoId);
            if (sum.IsNotNull())
            {
                sum.TimeSpan += studyLog.TimeSpan;
                sum.LastStudyTime = request.StudyTime;
                sum.UpdateTime = DateTime.Now;
                sum.UpdateUserId = userId;
                if (!sum.IsFinish) //如果已经看过了，并且结束了，就不再更新该字段，证明已经学习完成这个视频
                    sum.IsFinish = request.IsFinish;

                eVideoStudySumService.UpdateNoSaveChange(sum);
            }
            else
            {
                sum = new EVideoStudySum
                {
                    Id = Guid.NewGuid(),
                    PackageId = request.PackageId,
                    CourseId = request.CourseId,
                    ChapterId = request.ChapterId,
                    VideoId = request.VideoId,
                    UserId = userId,
                    IsDelete = false,
                    OrgCode = CurrentUserModel?.OrgCode ?? string.Empty,
                    CreateUserId = userId,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    UpdateUserId = userId,
                    IsUsed = true,
                    TimeSpan = studyLog.TimeSpan,
                    LastStudyTime = request.StudyTime,
                    IsFinish = request.IsFinish
                };

                eVideoStudySumService.AddNoSaveChange(sum);
            }

            eVideoStudySumService.SaveChange();

            var viewModel = new SubmitVideoLogViewModel { StudyLogId = studyLog.Id };

            return ServiceResponse<SubmitVideoLogViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }
    }
}